package com.kinglumi.ailighting.auth.service.auth.impl;

import com.kinglumi.ailighting.auth.entity.RoleInfo;
import com.kinglumi.ailighting.auth.entity.UserDetail;
import com.kinglumi.ailighting.auth.entity.UserInfo;
import com.kinglumi.ailighting.auth.service.biz.RoleInfoService;
import com.kinglumi.ailighting.auth.service.biz.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Lxin
 * @version 1.0
 * @date 2021/8/10 15:45
 */
@Slf4j
@Service("emailUserDetailsService")
public class EmailUserDetailsService implements UserDetailsService {

    @Autowired
    private UserInfoService userService;
    @Autowired
    private RoleInfoService roleInfoService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("开始登陆验证，邮箱为: {}", s);

        // 根据用户名验证用户
        UserInfo info1 = new UserInfo();
        info1.setEmail(s);
        UserInfo userInfo = userService.selectOne(info1);
        if (userInfo == null) {
            throw new UsernameNotFoundException("Mailbox does not exist, login failed.");
        }

        // 构建UserDetail对象
        UserDetail userDetail = new UserDetail();
        userDetail.setUserInfo(userInfo);
        List<RoleInfo> roleInfoList = roleInfoService.listRoleByUserId(userInfo.getId().toString());
        userDetail.setRoleInfoList(roleInfoList);
        return userDetail;
    }

}
